import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,Input, DatePicker, Button, Card,Icon,Row,Col,message,Modal
} from 'antd';
import styles from './style.less';
import moment from 'moment';
import SpreadList from './SpreadList';

const FormItem = Form.Item;

@connect(state => ({
  contentManager: state.contentManager,
}))
@Form.create()
export default class LiveAdd extends PureComponent {
  state = {
    id:-1,
    rsId:1,
    pageNo:1,
    pageSize:5,
    total:0,
    resultBtnTxt:"",
    resultContentId:-1,
    modalVisible:false,
    spreadListData:[],

    spreadStarttime: '',
    spreadEndtime: '',
    formLoading:false,

    showDetail:false,
  };

  ////初始化渲染后触发 整个过程只调用一次
  componentDidMount() {
    const { form , dispatch} = this.props;

    if(this.props.location.query) {
      var spreadId = this.props.location.query.spreadId;
      const showDetail = this.props.location.query.showDetail;
      if (spreadId) {
        if(showDetail){
          this.setState({
            showDetail:showDetail
          });
        }
        const params = {
          spreadId: spreadId
        };
        dispatch({
          type: 'contentManager/fetchGetSpreadById',  //请求的action
          payload: params,
          callback: (res) => {
            form.setFields({
              sellerName: {value: res.sellerName},
              spreadTitle: {value: res.spreadTitle},
              rsName: {value: res.rsName},
              spreadExpire: {value: [moment(res.startTime), moment(res.endTime)]},
            })
            this.setState({
              resultBtnTxt: res.activityTitle,
              resultContentId:res.contentId,
              spreadStarttime:moment(res.startTime).format('YYYY/MM/DD h:mm:ss'),
              spreadEndtime:moment(res.endTime).format('YYYY/MM/DD h:mm:ss'),
              rsId:res.rsId,
              id:spreadId,
            });
          }
        });
      }
    }
  }

  handleSubmit = () => {
    const { form ,dispatch} = this.props;
    const { spreadStarttime ,spreadEndtime,resultContentId,rsId,id} = this.state;

    this.setState({
      formLoading: true
    })

    form.validateFields(
      (err, values) => {
        if (!err) {
          values.spreadExpireStart = spreadStarttime;
          values.spreadExpireEnd = spreadEndtime;
          delete values.spreadExpire;
          values.resultContentId = resultContentId;

          values.rsId = rsId;
          values.spreadType = 1;
          if(this.state.id != -1) values.id = id;
          dispatch({
            type: 'contentManager/fetchSaveOrUpdateSpread',  //请求的action
            payload:values,
            callback:(res) =>{
              message.success(res.msg);
              setTimeout(this.cancelBack(),200);
            }
          });
        }
      }
    );
  }

  cancelBack = () => {
    history.go(-1);
  }

  openSelectModel = () => {
    this.setState({
      modalVisible: true,
      loadMethod: this.loadMethod(this.state.pageNo,this.state.pageSize)
    });
  }

  addSpread = (record,index) => {
    this.state.spreadListData.splice(index,1);
    this.setState({
      resultBtnTxt: record.title,
      resultContentId:record.id,
      spreadListData:this.state.spreadListData.concat([])
    });
    this.closeSpreadModal();
  }

  closeSpreadModal = () => {
    this.setState({
      modalVisible: false
    });
  }

  spreadListChange = (page, pageSize) => {
    this.setState({
      pageNo:page,
      pageSize:pageSize
    });

    this.loadMethod(page,pageSize)
  }

  loadMethod(pageNo,pageSize,searchText){
    const { dispatch } = this.props;
    const params = {
      rsId:this.state.rsId,
      pageNo: pageNo,
      pageSize: pageSize
    };
    if(searchText) params.searchText = searchText;
    if(this.state.id != -1) params.spreadId = this.state.id;
    dispatch({
      type: 'contentManager/fetchListSpreadResult',  //请求的action
      payload:params,
      callback:(res) =>{
        this.setState({
          spreadListData: res.list,
          total:res.total
        });
      }
    });
  }

  handleSearch = (value) => {
    const {pageNo,pageSize} = this.state;
    this.loadMethod(pageNo,pageSize,value)
  }

  onDataPickChange = (dates, dateStrings) => {
    this.setState({
      spreadStarttime: dateStrings[0],
      spreadEndtime: dateStrings[1]
    })
  }

render() {
    const { getFieldDecorator  } = this.props.form;
    const { resultBtnTxt ,total,pageNo,pageSize,spreadListData,modalVisible,formLoading,showDetail} = this.state;
    const RangePicker = DatePicker.RangePicker;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    return (

      <div>
        <Form
          hideRequiredMark
          style={{ marginTop: 8 }}
        >
          <Card title="基本信息">
            <FormItem {...formItemLayout} label="商户名称">
              {getFieldDecorator('sellerName', {
                rules: [{
                  required: true,
                  message: '请输入商户名称',
                }]
              })(
                <Input placeholder="商户名称" disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="直播活动标题">
              {getFieldDecorator('spreadTitle', {
                rules: [{
                  required: true,
                  message: '请输入直播活动标题',
                }]
              })(
                <Input placeholder="直播活动标题" disabled={showDetail} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="直播频道">
              {getFieldDecorator('rsName', {
                initialValue:'新疆949交通广播'
              })(
                <Input placeholder="优惠券标题" disabled={true}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="结果页面" >
                <Button  style={{width:'100%'}} onClick={()=>this.openSelectModel()} disabled={showDetail}  >{resultBtnTxt}</Button>
            </FormItem>
            <FormItem {...formItemLayout} label="摇一摇有效期">
              {getFieldDecorator('spreadExpire', {
                rules: [{
                  required: true,
                  message: '请选择有效期',
                }],
              })(
                <RangePicker
                  disabled={showDetail}
                  ranges={{ "今天": [moment(), moment()], '这个月': [moment(), moment().endOf('month')] }}
                  showTime
                  format="YYYY/MM/DD HH:mm:ss"
                  onChange={this.onDataPickChange}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Card>
          <FormItem {...formItemLayout}  >
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 20 }}>
            <Row gutter={16} style={{ marginBottom: '10px' }}>
              <Col className="gutter-row" span={9}>
              </Col>
              <Col className="gutter-row" span={3}>
                <Button type="primary" htmlType="submit" loading={formLoading}
                        onClick={() => this.handleSubmit()} disabled={showDetail} >保存</Button>
              </Col>
              <Col className="gutter-row" span={3}>
                <Button onClick={() => this.cancelBack()}>取消</Button>
              </Col>
              <Col className="gutter-row" span={9}>
              </Col>
            </Row>
          </FormItem>
          <Modal
            title="增加结果页面"
            visible={modalVisible}
            footer={null}
            onCancel={() => this.closeSpreadModal()}
          >
            <SpreadList
              spreadListData={spreadListData}
              onChange={this.spreadListChange}
              handleSearch={this.handleSearch}
              total = {total}
              pageNo = {pageNo}
              pageSize = {pageSize}
              addSpread = {this.addSpread}
            />
          </Modal>
        </Form>
      </div>
    );
  }
}
